/**
 * Copyright (c) 2012 Ben Murphy (Smurph)
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.smurph.expandablelist.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.DatabaseUtils.InsertHelper;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.smurph.expandablelist.provider.TblABC;
import com.smurph.expandablelist.provider.TblABC.ABCs;
import com.smurph.expandablelist.provider.TblName;
import com.smurph.expandablelist.provider.TblName.Names;

public class DBHelper extends SQLiteOpenHelper {

	public static final int mDBVersion = 1;
	public static final String mDBName = "Names.db";
	
	public DBHelper(Context context) {
		super(context, mDBName, null, mDBVersion);
	}
	
	@Override
	public void onCreate(SQLiteDatabase db) {
		InsertHelper iHelper = null;
		ContentValues cv = null;
		try {
			db.beginTransaction();

			db.execSQL(TblABC.mCreate_Table);
			iHelper = new InsertHelper(db, ABCs.TBL_ABC);
			cv = new ContentValues();
			for (String a : TblABC.abcs) {
				cv.put(ABCs.LETTER, a);
				iHelper.insert(cv);
				cv.clear();
			}			
			
			db.execSQL(TblName.mCreate_Table);

			iHelper = new InsertHelper(db, Names.TBL_NAMES);
			cv = new ContentValues();
			for (String a : TblName.names) {
				cv.put(Names.NAME, a);
				cv.put(Names.ABC_ID, getGroupID(a.substring(0, 1)));
				iHelper.insert(cv);
				cv.clear();
			}

			db.setTransactionSuccessful();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			db.endTransaction();
			cv.clear();
			iHelper.close();
		}
	}
	
	private int getGroupID(String letter) {
		int i = 1;
		for(String a : TblABC.abcs) {
			if (a.equalsIgnoreCase(letter)) break;
			else i++;
		}
		return i;
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// Do nothing for now.
	}
}
